// 导入express
const express = require('express')
// 导入cors(处理)
const cors = require('cors')
// 导入body-parser
const bodyParser = require('body-parser')
// 导入jwt
const jwtConfig = require('./jwt/index')
// 导入express_jwt
const { expressjwt: jwt } = require('express-jwt')

const Joi = require('joi')



// 导入路由模块
const loginRouter = require('./router/login.js')
const userInfoRouter = require('./router/userInfo.js')
const setRouter = require('./router/setting.js')
const productRouter = require('./router/product.js')
const messageRouter = require('./router/message.js')
const fileRouter = require('./router/file.js')
const loginLogRouter = require('./router/login_log.js')
const operationLogRouter = require('./router/operation_log.js')




const appServer = express()
const multer = require("multer");
// 在server服务端下新建一个public文件，在public文件下新建upload文件用于存放图片
const upload = multer({
  dest: './public/upload'
})
appServer.use(upload.any())
// 静态托管
// app.use(express.static(path.join(__dirname, 'dist')));
appServer.use(express.static("./public"));


// 跨域中间件
appServer.use(cors())
// urlencoded解析
appServer.use(bodyParser.urlencoded({ extended: false }))
// json解析
appServer.use(bodyParser.json())

appServer.use((req, res, next) => {
  // status: 0 为成功
  // status: 1 为失败
  // 默认设为1 ，方便处理失败的情况
  res.cc = (err, status = 1) => {
    res.send({
      status,
      message: err instanceof Error ? err.message : err
    })
  }
  next()
})
appServer.use(jwt({
  secret: jwtConfig.jwtSecretKey,
  algorithms: ['HS256']
}).unless({
  path: [/^\/api\//]
}))

// 错误级别中间件 对不符合joi规则的情况进行报错
appServer.use((err,req, res, next) => {
  // 
  if(err instanceof Joi.ValidationError) return res.cc(err)
  next()
})

appServer.use('/api', loginRouter)
appServer.use('/user', userInfoRouter)
appServer.use('/set', setRouter)
appServer.use('/pro', productRouter)
appServer.use('/msg', messageRouter)
appServer.use('/file', fileRouter)
appServer.use('/llog', loginLogRouter)
appServer.use('/olog', operationLogRouter)



appServer.listen(3007, () => {
  console.log('http://127.0.0.1:3007')
})


